package com.dc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.ResponseResultVO;
import com.dc.entity.WorkDetails;
import com.dc.entity.ro.WorkDetailsRO;
import com.dc.mapper.WorkDetailsMapper;
import com.dc.service.WorkDetailsService;
import com.dc.util.SnowflakeIdWorker;
import com.dc.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class WorkDetailsServiceImpl extends ServiceImpl<WorkDetailsMapper, WorkDetails> implements WorkDetailsService {

    @Resource
    private WorkDetailsMapper workDetailsMapper;


    @Override
    public ResponseResultVO insertWorkDetails(WorkDetailsRO ro) {
        WorkDetails workDetails = new WorkDetails();
        BeanUtils.copyProperties(ro, workDetails);
        workDetails.setId(SnowflakeIdWorker.generateId());
        return ResponseResultVO.insertResult(workDetailsMapper.insert(workDetails));
    }

    @Override
    public ResponseResultVO updateWorkDetails(WorkDetailsRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        WorkDetails workDetails = new WorkDetails();
        BeanUtils.copyProperties(ro, workDetails);
        return ResponseResultVO.updateResult(workDetailsMapper.updateById(workDetails));
    }

    @Override
    public ResponseResultVO deleteWorkDetails(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        return ResponseResultVO.deleteResult(workDetailsMapper.deleteBatchIds(idList));
    }

    @Override
    public ResponseResultVO selectWorkDetailsByPage(WorkDetailsRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        QueryWrapper<WorkDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(ro.getType()), WorkDetails::getType, ro.getType());
        queryWrapper.lambda().eq(StringUtils.isNotBlank(ro.getProjectName()), WorkDetails::getProjectName, ro.getProjectName());
        queryWrapper.lambda().orderByDesc(WorkDetails::getCreateTime);
        return ResponseResultVO.resultList(workDetailsMapper.selectPage(page, queryWrapper), ro);

    }

    @Override
    public ResponseResultVO selectWorkDetailsList() {
        List<WorkDetails> workDetails = workDetailsMapper.selectList(new QueryWrapper<>());
        return ResponseResultVO.successResult(workDetails.stream().collect(
                Collectors.groupingBy(
                        s -> s.getType()
                )));
    }
}
